package cn.edu.zwu.service;

import cn.edu.zwu.dao.User;

import java.util.ArrayList;
import java.util.List;

public class UserService {
    private MailService mailService;
    private PhoneService phoneService;

    public void setPhoneService(PhoneService phoneService) {
        this.phoneService = phoneService;
    }

    public void setMailService(MailService mailService) {
        this.mailService = mailService;
    }

    private List<User> users = new ArrayList<>(List.of( // users:
            new User(1, "Bob", "password", "bob@example.com", "123456"), // bob
            new User(2, "Alice", "password", "alice@example.com"), // alice
            new User(3, "Tom", "password", null, "1234567"))); // tom

    public User login(String userName, String password) {
        for (User user : users) {
            if (user.getUserName().equalsIgnoreCase(userName) && user.getPassword().equals(password)) {
                if(user.getMail() != null) {
                    mailService.sendLoginMail(user);
                }
                if(user.getPhone() != null) {
                    phoneService.sendLoginSMS(user);
                }
                return user;
            }
        }
        throw new RuntimeException("login failed.");
    }

    public boolean isValidUser(User user){
        return user.getUserName().length() < 20;
    }

    public User register(long id, String username, String password, String mail, String phone) {
        User newUser = new User(id, username, password, mail, phone);
        if (isValidUser(newUser)){
            users.add(newUser);
            if(newUser.getMail() != null) {
                mailService.sendRegistrationMail(newUser);
            }
            if(newUser.getPhone() != null) {
                phoneService.sendRegistrationSMS(newUser);
            }
            return newUser;
        }
        return null;

    }

    public User getUser(long id) {
        return this.users.stream().filter(user -> user.getId() == id).findFirst().orElseThrow();
    }
}
